/**
 * this file will be loaded before server started
 * you can define global functions used in controllers, models, templates
 */

/**
 * use global.xxx to define global functions
 * 
 * global.fn1 = function(){
 *     
 * }
 */
var request = require('request');


global.isEmptyObject = function(e) {
	var t;
	for (t in e)
		return !1;
	return !0
}
global.getUrlParam = function(url, key) {
	var reg = new RegExp("(^|&|\\?)" + key + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = url.match(reg); //匹配目标参数
	if (r != null) return unescape(r[2]);
	return null; //返回参数值
}

global.httpGet = function(url, param, isJson = true) {
	return new Promise(function(resolve, reject) {
		request({
			url: url,
			qs: param,
			method: 'GET',
			json: isJson
		}, function(error, response, body) {
			if (error) {
				resolve({
					code: 500,
					desc: error
				});
			} else {
				resolve(body);
			}
		});
	});
}

global.httpPost = function(url, param, isJson = true) {
	return new Promise(function(resolve, reject) {
		request({
			url: url,
			body: param,
			json: isJson,
			method: 'POST'
		}, function(error, response, body) {
			if (error) {
				resolve({
					code: 500,
					desc: error
				});
			} else {
				resolve(body);
			}
		});
	});
}

global.httpForm = function(url, param) {
	return new Promise(function(resolve, reject) {
		request({
			url: url,
			formData: param,
			form: true,
			method: 'POST'
		}, function(error, response, body) {
			if (error) {
				resolve({
					code: 500,
					desc: error
				});
			} else {
				resolve(body);
			}
		});
	});
}

global.httpTokenPost = async function(url, param, ctrl, withToken = true) {
	if (withToken) {
		param.token = await ctrl.session('token');
	}
	param.echo = ctrl.http.module + '.' + ctrl.http.controller + '.' + ctrl.http.action;
	param.timestamp = new Date().getTime();
	console.log('param ==>', param);
	let res = await httpPost(url, param);
	console.log('result ==>', res);
	if (res && res.code == 200) {
		await ctrl.session('token', res.result.token)
	}
	return res;
}